<?php $this->load->view('common/admin_header');?>
<link rel="stylesheet" type="text/css" href="<?=base_url('themes/admins/js/fancybox/jquery.fancybox-1.3.4.css')?>" media="screen" />
<script type="text/javascript" src="<?=base_url('themes/admins/js/fancybox/jquery.fancybox-1.3.4.pack.js')?>"></script>
<style type="text/css">
  .spec-name{text-align: right;}
  .spec-items{text-align:left; font-weight: normal;padding:10px 0;}
  .spec-items span{padding:5px 10px;border: 1px solid #eee;margin:2px 5px;cursor:pointer;display: inline-block;min-width:50px;text-align: center;}
  .spec-items span input[type="checkbox"] {display: none;}
  .spec-items span.on{border:1px solid #8bc34a;background-color: #8bc34a;color: #fff;}
  .price-text{padding:3px 5px;width:100px;}
</style>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
  $("#thumbnail").fancybox({
    helpers:{occasion:{type:'float'}}
  });
});
</script>
<div class="block withsidebar">
  <div class="block_head">
    <div class="bheadl"></div>
    <div class="bheadr"></div>
    <h2><?=$lang['global_lable_36']?></h2>
    <ul>
      <li><a href="<?=site_url('admins/products').'?'.base64_decode($this->input->cookie('url_query'))?>"><?=$lang['global_lable_41']?></a></li>
    </ul>
  </div>
  <!-- .block_head ends -->
  <div class="block_content">
  <form id="form" name="form" action="<?=site_url('admins/products/modify')?>" method="post">
    <input type="hidden" name="edit_id" id="edit_id" value="<?=set_value('edit_id',isset($edit_id)?$edit_id:'')?>" />
      <div class="sidebar">
        <ul class="sidemenu">
          <li><a href="#sb"><?=$lang['global_lable_33']?></a></li>
          <?php foreach($languages->result_array() as $k=>$lg):?>
          <li><a href="#sb<?=$lg['id']?>"><?=$lg['name']?></a></li>
          <?php endforeach;?>
        </ul>
        <br/>
        <p>
          <input id="button1" class="btn btn-block btn-primary" type="submit" name="btn_save" value="<?=$lang['global_lable_12']?>" />
        </p>
        <p>
          <input id="button2" class="btn btn-block" type="reset" value="<?=$lang['global_lable_13']?>"/>
        </p>
      </div>
      <!-- .sidebar ends -->
    <div class="sidebar_content" id="sb">
      <?php $CI=& get_instance();?>
      <?php $this->load->view('common/notify');?>
      <div class="sctitle"><i class="icon-pencil"></i> <?=$lang['global_lable_33']?></div>
      <?php $img_main_image=set_value('main_image',isset($main_image) && file_exists($main_image)?$main_image:'');?>
      <?php $show_image=!empty($img_main_image)?imagelib::resize_thumb($img_main_image,260,260):'themes/admins/img/no_image.png';?>
      <p>
        <a id="thumbnail" href="<?=base_url().(!empty($img_main_image)?$img_main_image:'themes/admins/img/no_image.png')?>" class="thumbnail">
          <img id="img_main_image" src="<?=base_url().$show_image?>" class="preview-img" style="max-width:300px">
        </a>
      </p>
      <p>
        <label><?=$lang['content_lable_10']?>:</label>
        <span class="upload">
        <div id="simple-btn" data-tag="display_logo" class="btn btn-success js-fileapi-wrapper">
           <div class="js-browse">
              <input type="file" name="Filedata">
           </div>
           <div class="js-upload" style="display: none">
              <div class="progress progress-success">
                <div class="js-progress bar"></div>
              </div>
              <span class="btn-txt">Uploading (<span class="js-size"></span>)</span>
           </div>
        </div>
        </span>
        <input id="old_main_image" type="hidden" name="main_image" value="<?=set_value('main_image',isset($main_image) && file_exists($main_image)?$main_image:'')?>">
        <a href="#clear_img" tag="main_image" class="btn" style="display:<?=!empty($img_main_image)?'':'none'?>"><i class="icon-trash"></i> <?=$lang['content_lable_39']?></a>
      </p>


            <label><?=$lang['content_lable_24']?>:</label>
            <div id="show_images" >
                <ul>

                    <?php if(isset($photo) && $photo>0):?>
                        <?php foreach($photo as $image):?>
                            <?php $pimage=set_value('photo',isset($image) && file_exists($image)?$image:'');?>
                            <?php $show_img=!empty($pimage)?imagelib::resize_thumb($pimage,160,160):'themes/admins/img/no_image.png';?>
                            <li style="float:left">
                                <input type="hidden" name="photo[]" value="<?=$image?>"/>&nbsp;
                                <img id="pimage" class="edit_image img-polaroid" src="<?=base_url().$show_img?>" />
                                <p style="margin-left: 60pt;"><a class="swfupload_delete" href='#' style="margin-top: ">[<?=$lang['global_lable_25']?>]</a></p>
                            </li>
                        <?php endforeach;?>
                    <?php else:?>
                        <div class="alert alert-info"><p><?=$lang['content_lable_25']?></p><a id="bulk_uploads_button" href="#" class="btn btn-inverse"><?=$lang['content_lable_26']?></a></div>
                    <?php endif;?>
                </ul>

            </div>
            <!--      <div id="batch_images" class="block_content" style="display:none;min-height:150px;text-align:center;">-->
            <div id="batch_images" class="" style="display:none;">
                <!--批量插入多語言描述-->
                <div id="batch_description" style="display:none">

                </div>
                <div class="operate">
                    <!-- 上傳按鈕 -->
                    <div id="bulk-uploads" class="btn btn-success js-fileapi-wrapper" style="margin-right: 1000pt;">
                        <div class="js-browse">
                            <input type="file" name="Filedata" >
                        </div>
                        <div class="js-upload" style="display: none">
                            <div class="progress progress-success">
                                <div class="js-progress bar"></div>
                            </div>
                            <span class="btn-txt">Uploading (<span class="js-size"></span>)</span>
                        </div>
                    </div>
                </div>
                <ul id="myul" style="margin-top: 20pt;">


                </ul>
                <p id="divFileProgressContainer" style="clear:both;"></p>
            </div><!--批量上傳結束-->

        <p style="clear:both">
        <label><?=$lang['content_lable_28']?>:</label>
        <select name="category_id" id="category_id">
         <option value=""><?=$lang['content_lable_27']?></option>
         <?php if(!empty($categorys)):?>
         <?php foreach ($categorys as $list):?>
         <option value="<?=$list['id']; ?>" <?=set_select('category_id',$list['id'])?> <?=isset($category_id) && $category_id==$list['id']?'selected':''?> ><?=$list['title']; ?></option>
         <?php endforeach; ?>
         <?php endif;?>
        </select>
        <span class="note required">*<?=$lang['global_lable_35']?></span>
      </p>
      <!--属性规格-->
      <div id="product-spec">
        
      </div>
      <p>
        <label><?=$lang['content_lable_6']?>:</label>
        <select name="product_unit_id" id="product_unit_id">
         <option value=""><?=$lang['content_lable_27']?></option>
         <?php if(!empty($productunits)&&$productunits->num_rows()>0):?>
         <?php foreach ($productunits->result_array() as $list):?>
         <option value="<?=$list['id']; ?>" <?=set_select('product_unit_id',$list['id'])?> <?=isset($product_unit_id) && $product_unit_id==$list['id']?'selected':''?> ><?=$list['name']; ?></option>
         <?php endforeach; ?>
         <?php endif;?>
        </select>
        <span class="note required">*<?=$lang['global_lable_35']?></span>
      </p>
      <p>
        <label><?=$lang['content_lable_42']?>:</label>
        <select name="is_spec" id="is_spec">
          <option value=""><?=$lang['content_lable_27']?></option>
          <option value="1" <?=set_select('is_spec',1)?> <?=isset($is_spec) && $is_spec==1?'selected':''?>><?=$lang['content_lable_43']?></option>
          <option value="2" <?=set_select('is_spec',2)?> <?=isset($is_spec) && $is_spec==2?'selected':''?>><?=$lang['content_lable_44']?></option>
        </select>
          <span class="note required">*<?=$lang['global_lable_35']?></span>
      </p>
      <p>
        <label><?=$lang['content_lable_51']?>:</label>
        <select name="pos_id" id="pos_id">
          <?php if(!empty($posname)):?>
            <?php foreach($posname as $pos):?>
          <option value="<?=$pos['id']?>" <?php if(isset($pos_id) && $pos_id == $pos['id']){echo "selected";}?> ><?=$pos['pos_title']?></option>
        <?php endforeach;?>
        <?php endif;?>
        </select>
      </p>
      <p>
        <label><?=$lang['global_lable_17']?>:</label>
        <input type="text" class="text small" name="sort_order" value='<?=set_value('sort_order',isset($sort_order)?$sort_order:0)?>'/>
      </p>
      <p>
        <label><?=$lang['content_lable_29']?>:</label>
        <input type="text" class="text small" name="old_price" value='<?=set_value('old_price',isset($old_price)?$old_price:'')?>'/>
      </p>
      <p>
        <label><?=$lang['content_lable_30']?>:</label>
        <input type="text" class="text small" name="price" id="_price" value='<?=set_value('price',isset($price)?$price:'')?>'/>
      </p>
       <p>
        <label><?=$lang['content_lable_31']?>:</label>
        <input type="text" class="text small" name="stock" value='<?=set_value('stock',isset($stock)?$stock:'')?>'/>
      </p>
      <p>
        <label><?=$lang['global_lable_18']?>:</label>
        <input type="text" class="text Wdate small" onFocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',lang:'zh-tw'})" name="add_time" value='<?=set_value('add_time',isset($add_time)?date($format_time,$add_time):date($format_time))?>'/>
      </p>
      <p>
        <label><?=$lang['global_lable_19']?>:</label>
        <input type="text" class="text Wdate small" onFocus="WdatePicker({dateFmt:'yyyy-MM-dd HH:mm:ss',lang:'zh-tw'})" name="update_time" value='<?=set_value('update_time',isset($update_time)?date($format_time,$update_time):date($format_time))?>'/>
      </p>
      <p>
        <label><?=$lang['global_lable_16']?>:</label>
        <input type="radio" class="radio" name="status" value="1" <?=set_radio('status', '1', TRUE); ?> <?=isset($status) && $status==1?'checked':''?> />
        <span><?=$lang['global_lable_37']?></span>
        <input type="radio" class="radio" name="status" value="2" <?=set_radio('status', '2'); ?> <?=isset($status) && $status==2?'checked':''?> />
        <span><?=$lang['global_lable_38']?></span>
      </p>
      </div>
      <?php $lang_num=$languages->num_rows();?>
      <?php foreach($languages->result_array() as $lgs):?>
      <?php $k=$lgs['id'];?>
      <div class="sidebar_content" id="sb<?=$k?>">
        <?php if($lang_num>1):?>
        <div class="sctitle"><i class="icon-pencil"></i> <?=$lgs['name']?>&nbsp;&nbsp;<a href="javascript:void(0)" class="sync_lang" lang-num="<?=$lang_num?>" lang-id="<?=$k?>" occasion="<?=$lang['global_lable_44']?>"><?=$lang['global_lable_45']?></a></div>
        <?php else:?>
        <div class="sctitle"><i class="icon-pencil"></i> <?=$lgs['name']?></div>
        <?php endif;?>
      <p>
        <label><?=$lang['global_lable_15']?>:</label>
        <input type="text" value="<?=set_value('descriptions['.$k.'][title]',isset($descriptions[$k]['title'])?$descriptions[$k]['title']:'')?>" class="text small" name="descriptions[<?=$k?>][title]">
        <span class="note required">*<?=$lang['global_lable_35']?></span>
      </p>
      <p>
        <label><?=$lang['content_lable_32']?>:</label>
        <input type="text" value="<?=set_value('descriptions['.$k.'][introduction]',isset($descriptions[$k]['introduction'])?$descriptions[$k]['introduction']:'')?>" class="text small" name="descriptions[<?=$k?>][introduction]">
      </p>
      <p>
          <label><?=$lang['content_lable_33']?>:</label>
          <input type="text" value="<?=set_value('descriptions['.$k.'][number]',isset($descriptions[$k]['number'])?$descriptions[$k]['number']:'')?>" class="text small" name="descriptions[<?=$k?>][number]">
      </p>
      <p style="display:">
        <label><?=$lang['content_lable_34']?>:</label>
        <textarea id="description<?=$k?>" name="descriptions[<?=$k?>][content]"><?=set_value('descriptions['.$k.'][content]',isset($descriptions[$k]['content'])?$descriptions[$k]['content']:'')?></textarea>
      </p>
      </div>
      <?php endforeach;?>
    </form>
  </div>
  <!-- .block_content ends -->
  <div class="bendl"></div>
  <div class="bendr"></div>
</div>
<!-- .block ends -->
<script type="text/javascript" charset="utf-8">
window.FileAPI = {
  debug: true, // debug mode
  cors: false,    // if used CORS, set `true`
  flashUrl:"<?=base_url('themes/admins/js/jquery.fileapi/FileAPI/FileAPI.flash.swf')?>",
  staticPath:'themes/admins/js/jquery.fileapi/FileAPI/' // path to *.swf
};
</script>
<script src="<?=base_url('themes/admins/js/jquery.fileapi/FileAPI/FileAPI.min.js')?>"></script>
<script src="<?=base_url('themes/admins/js/jquery.fileapi/FileAPI/FileAPI.exif.js')?>"></script>
<script src="<?=base_url('themes/admins/js/jquery.fileapi/jquery.fileapi.js')?>"></script>
<script src="<?php echo base_url('themes/admins/js/tinymce/tinymce.min.js')?>"></script>
<script>tinymce.init({ 
  selector:'textarea' ,
  plugins: 'image code media advcode advlist textcolor insertdatetime link hr colorpicker autoresize bbcode',
  toolbar: 'undo redo align forecolor backcolor | link image media | code insertdatetime',
  relative_urls: true,
  // we override default upload handler to simulate successful upload
  images_reuse_filename: false,
  images_upload_url: "<?=site_url('admins/upload/image_upload')?>",
  language:'zh_TW',
  forced_root_block:'p',

});</script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function($) {
  var folder=encodeURIComponent('uploads/products/');
  $('#simple-btn').fileapi({
     url:"<?=site_url('admins/upload/single_upload')?>",
     data: {'folder':folder,'_size':'260x260','_element_id':'main_image','_admin_id':"<?=$this->nsession->userdata('admin_id')?>",'_nickName':"<?=$this->nsession->userdata('nick_name')?>"},
     multiple: false,
     accept: 'image/*',
     maxSize: 2 * FileAPI.MB,
     autoUpload: true,
     clearOnComplete:true,
     elements: {
        size: '.js-size',
        active: { show: '.js-upload', hide: '.js-browse' },
        progress: '.js-progress'
     },
     onComplete:function(evt,uiEvt){
      var error = uiEvt.error;
      var result = uiEvt.result; // server response
      if(!error && result){
        // console.log(result);
        if(result.error){
          alert(result.error);
          return;
        }
        $("#old_"+result.element_id).val(result.img_path);
        $("#img_"+result.element_id).attr('src',result.thumb_img);
        if ($('#thumbnail').length)
          $("#thumbnail").attr('href',result.http_img);
        if ($('a[href="#clear_img"]').length)
          $('a[href="#clear_img"]').show();
      }
    }
  });

  //清除圖片
  $('a[href="#clear_img"]').click(function() {
    var obj=$(this);
    var action="<?=site_url('admins/upload/delete')?>";
    var defaule_img="<?=base_url('themes/admins/img/no_image.png')?>";
    clear_img(obj,action,defaule_img);
    return false;
  });
  $("#category_id").change(function(){
    var cat_id = $(this).val()*1;
    if(cat_id > 0){
      $.post("<?php echo base_url('admins/specs/getSpecIems')?>",{cat_id:cat_id,product_id:$('#edit_id').val()},function(html){
          $("#product-spec").html(html);
          setSpecInpunt();
      })
    }
  })
  if($("#category_id").val()*1 > 0){
    $("#category_id").change();
  }
  $("body").on("click",".spec_item",function(){
       var _this = $(this);
       if(_this.hasClass('on')){
          _this.removeClass("on");
          _this.find("input").prop('checked',false);
       }else{
          _this.addClass("on");
          _this.find("input").prop('checked',true);
       }
       setSpecInpunt();
   });
    $("body").on("click",".attr_item",function(){
        var _this = $(this);
        if(_this.hasClass('on')){
            _this.removeClass("on");
        }else{
            _this.addClass("on");
        }
        setAttrInpunt()
    });

    //批量上傳
    $("#bulk_uploads,#bulk_uploads_button").click(function(){
        $("#show_images").toggle();
        $("#batch_images").toggle();
        return false;
    });
    var folder='products';
    //上傳方法
    $('#bulk-uploads').fileapi({
        url:"<?=base_url('admins/upload/bulk_uploads')?>",
        data: {'folder':folder,'_size':'260x260','_element_id':'Filedata'},
        accept: 'image/*',
        maxSize: 2 * FileAPI.MB,
        autoUpload: true,
        clearOnComplete:true,
        multiple: true,
        elements: {
            size: '.js-size',
            active: { show: '.js-upload', hide: '.js-browse' },
            progress: '.js-progress'
        },
        onFileComplete:function(evt,uiEvt){
            var error = uiEvt.error;
            var result=uiEvt.result;
            if(!error && result){
                //console.log(result);
                if(result.error){
                    alert(result.error);
                    return;
                }
                addImage(result);//預覽圖片
            }
        }
    });

    //打印臨時上傳圖片
    function addImage(obj) {
        var batch_description = $('#batch_description').html();
        var htmls='<li style="float:left;"><input type="hidden" name="photo[]" value="'+obj.img_path+'">';
        htmls+='<img style="padding:15pt;" src="'+obj.thumb_img+'">';
        if (batch_description!='') {
            htmls+=batch_description;
        }else{
//            htmls+='<p><span>描述:</span><input type="text" style="width:150px" name="description[]"></p>';
            htmls+='';
        }
        //htmls+='<p><span>描述:</span><input type="text" style="width:150px" name="description[]"></p>';
//        htmls+='<p><span>排序:</span><input type="text" style="width:150px" name="sort_order[]"></p>';
        htmls+='<p style="margin-left: 60pt;"><a class="swfupload_delete" href="'+obj.delete_url+'">[刪除]</a></p>';
        htmls+="</li>"
        $("#myul").append(htmls).fadeIn('slow', 1);
        $("#btn_sub").show();
    }

});
function setSpecInpunt(){
    var items = $(".spec-items").find(".spec_item.on");
    var items = $(".spec-items").find(".spec_item.on");
    var spec_arr = {};
    $.each(items,function(i,item){
        //spec_arr.push($(item).data('key'))
        var spec_id = $(item).data('spec');
        var item_id = $(item).data('item');
        if(!spec_arr.hasOwnProperty(spec_id)) spec_arr[spec_id] = [];
        spec_arr[spec_id].push(item_id);
    })
    _loading();
    $.post("<?php echo base_url('admins/specs/getSpecItemInput')?>",{cat_id:$("#category_id").val(),spec_arr:spec_arr,'product_id':$('#edit_id').val(),'price':$("#_price").val()},function(html){
        $("#product-spec").find('#spec_item_input').html(html);
        _removeLoading()
    })
}
function setAttrInpunt(){
    var items = $(".spec-items").find(".attr_item.on");
    var attr_arr = {};
    $.each(items,function(i,item){
        //spec_arr.push($(item).data('key'))
        var spec_id = $(item).data('spec');
        var item_id = $(item).data('item');
        if(!attr_arr.hasOwnProperty(spec_id)) attr_arr[spec_id] = [];
        attr_arr[spec_id].push(item_id);
    })
    _loading();
    $.post("<?php echo base_url('admins/specs/getAttrItemInput')?>",{cat_id:$("#category_id").val(),attr_arr:attr_arr,'product_id':$('#edit_id').val()},function(html){
        $("#product-spec").find('#attr_item_input').html(html);
        _removeLoading()
    })
}
  $("body").on('click','.swfupload_delete',function(){
    if(confirm('您確定刪除該圖片嗎?')){
      $(this).parent().parent().remove();
    }
      return false;
  })
</script>
<?php $this->load->view('common/admin_footer');?>